<?php
//登录业务模块
class LoginService extends TP_Service {
    public $redis;

    public function __construct() {
        parent::__construct();
        $this->load->Model("PModel/Account_model");
        $this->load->Model("SModel/Login_history_model");

        $this->redis = $this->newRedis();
    }

    /**
     * [login description]
     * @Description 账号密码登录，仅完成登录业务
     * @Author      FengPQ
     * @DateTime    2020-05-19T10:41:11+0800
     * @param       [type]                   $usercode [账号]
     * @param       [type]                   $password [密码]
     * @param       [type]                   $accountType [用户类型，按accountType枚举]
     * @return      [type]                             [description]
     */
    public function login($usercode, $password, $accountType) {
        //为空判断
        api_params_check($usercode, $password, $accountType);

        //用户类型不正确
        if (AccountType::Admin[TPEnum::Value] != $accountType && AccountType::Cust[TPEnum::Value] != $accountType) {
            throw new \TPException(ErrCode::ErrCode_10003);
        }

        if ($accountType == AccountType::Admin[TPEnum::Value]) {
            $where = array("usercode" => $usercode);
        } else {
            $where = array("email" => $usercode);
        }
        //用户类型判断，并获取基本用户信息
        $accountInfo = $this->Account_model->get_single($where);

        //用户不存在
        if (!$accountInfo) {
            throw new \TPException(ErrCode::ErrCode_10403);
        }

        //无效用户情况
        if ($accountInfo['valid'] != EnableState::Enable[TPEnum::Value]) {
            throw new \TPException(ErrCode::ErrCode_10401);
        }


        if ($accountType == AccountType::Admin[TPEnum::Value]) {
            //用户密码判断
            $password_confirm = getPasswrodWithTwiceEncode($password, $accountInfo['passsalt']);
            if ($password_confirm != $accountInfo['password']) {
                throw new \TPException(ErrCode::ErrCode_10402);
            }
        } else {
            //邮箱验证码判断
            $code = $this->redis->get("pattern:email:" . $usercode);
            if ($code != $password) {
                throw new \TPException(ErrCode::ErrCode_10301);
            }
        }



        //生成登录token
        $this->load->service("PService/SecurityService");
        $this->SecurityService->loginAccess($accountInfo['uuid']);
    }

    //退出登陆
    public function destory_login($uuid) {
        // 推送的url地址，上线时改成自己的workerman服务器地址
        $push_api_url = $_SERVER['SERVER_NAME'] . ":2121";
        $post_data = array(
            'type' => 'destory_login',
            'content' => '退出登陆',
            'to' => $uuid,
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $push_api_url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Expect:"));
        $return = curl_exec($ch);
        curl_close($ch);
    }

    //微信登录
    public function wxLogin() {
        if (!isset($_SESSION['weixin_user'])) {
            $con = $this->router->fetch_class(); //获取控制器名
            $func = $this->router->fetch_method(); //获取方法名

            $appid = WX_APP_ID;
            if (!isset($_GET['code'])) {
                $dizhi = urlencode(site_url($con . '/' . $func));
                header('location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . $dizhi . '&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect');
            } else {
                $code = $_GET['code'];
                $state = $_GET['state'];
                //换成自己的接口信息
                $appid = WX_APP_ID;
                $appsecret = WX_APP_SECRET;
                if (empty($code)) {
                    $this->error('授权失败');
                }

                $token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code';
                $token = json_decode(file_get_contents($token_url));
                if (isset($token->errcode)) {
                    echo '<h1>错误：</h1>' . $token->errcode;
                    echo '<br/><h2>错误信息：</h2>' . $token->errmsg;
                    exit;
                }
                $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=' . $appid . '&grant_type=refresh_token&refresh_token=' . $token->refresh_token;
                //转成对象
                $access_token = json_decode(file_get_contents($access_token_url));
                if (isset($access_token->errcode)) {
                    echo '<h1>错误：</h1>' . $access_token->errcode;
                    echo '<br/><h2>错误信息：</h2>' . $access_token->errmsg;
                    exit;
                }
                $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token->access_token . '&openid=' . $access_token->openid . '&lang=zh_CN';
                //转成对象
                $user_info = json_decode(file_get_contents($user_info_url));
                if (isset($user_info->errcode)) {
                    echo '<h1>错误：</h1>' . $user_info->errcode;
                    echo '<br/><h2>错误信息：</h2>' . $user_info->errmsg;
                    exit;
                }

                $rs = json_decode(json_encode($user_info), true); //返回的json数组转换成array数组

                //打印用户信息
                //echo '<pre>';
                // var_dump($token);
                // var_dump($access_token);
                //echo '</pre>';
                //获取open_id对应手机号

            }
            // $_SESSION['refresh']=$token->refresh_token;
            $_SESSION['weixin_user'] = $rs;
        }
        // $_SESSION['weixin_user']['openid']=1;
    }



    //获取ip地址
    private  function getIp() {
        $onlineip = '';
        if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $onlineip = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $onlineip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $onlineip = getenv('REMOTE_ADDR');
        } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $onlineip = $_SERVER['REMOTE_ADDR'];
        }
        return $onlineip;
    }




    //获取ip地理位置
    private function GetIpLookup($ip) {
        $amap = $this->config->item('amap')['key'];
        // $ip = $this->getIp();
        if (empty($ip)) {
            return false;
        }
        $res = file_get_contents("https://restapi.amap.com/v5/ip?ip=$ip&type=4&key=$amap");
        if (empty($res)) {
            return false;
        }
        $json = json_decode($res, true);
        if ($json['status'] == 0) {
            return false;
        }
        
        $address = $json['country'];

        if(isset($json['province'])) $address.=$json['province'];

        if(isset($json['city'])) $address.=$json['city'];
        if(isset($json['district'])) $address.=$json['district'];

        
        return $address;
    }


    //保存登录历史
    public function saveLoginHistory(){
        $this->load->service("SService/UserInfoService");

        $user = $this->UserInfoService->userInfo();

        // var_dump($user);

        $ip = $this->getIp();

        // $address = $this->GetIpLookup($ip);

        $add = array(
            'name' => $user['username'],
            'usercode' => $user['usercode'],
            'mobile' => $user['mobile'],
            'email' => $user['email'],
            'ip' => $ip,
           // 'ip_address' => $address,
           'ip_address' => '0',
            'created' => date('Y-m-d H:i:s')
        );
        $this->Login_history_model->add($add);
        return true;
    }
}
